﻿Imports Org.BouncyCastle
Imports Org.BouncyCastle.Crypto.Generators
Imports Org.BouncyCastle.Crypto
Imports Org.BouncyCastle.Security
Imports Org.BouncyCastle.Crypto.Prng
Imports Org.BouncyCastle.X509
Imports Org.BouncyCastle.Asn1.X509
Imports Org.BouncyCastle.Asn1.Pkcs
Imports Org.BouncyCastle.Math
Imports Org.BouncyCastle.Asn1
Imports System.Xml
Imports System.IO
Imports System.Xml.Serialization
Imports Org.BouncyCastle.Pkcs

Public Class MyCertificateManager


    Public Shared Sub GenerateMyCertificate()
        Dim kp = SharedTools.KeysAndDigestsUtilities.GenerateRSAKeypair(4096)
        GenerateMyCertificate(kp)
    End Sub

    Public Shared Sub GenerateMyCertificate(keylength As Object)
        Dim kp = SharedTools.KeysAndDigestsUtilities.GenerateRSAKeypair(DirectCast(keylength, Integer))
        GenerateMyCertificate(kp)
    End Sub

    Public Shared Sub GenerateMyCertificate(kp As AsymmetricCipherKeyPair)
        Repository.Data = New CAdata
        Dim cadata = Repository.Data

        Dim gen = New X509V3CertificateGenerator()

        Dim certName = New X509Name("CN=CA, O=Math.UniPD, OU=Sicurezza")
        Dim serialNo = BigInteger.ProbablePrime(128, New Random())

        gen.SetSerialNumber(serialNo)
        gen.SetSubjectDN(certName)
        gen.SetIssuerDN(certName)
        gen.SetNotBefore(DateTime.Now)
        gen.SetNotAfter(DateTime.Now.AddYears(20))
        gen.SetSignatureAlgorithm("SHA512withRSA")
        gen.SetPublicKey(kp.Public)

        gen.AddExtension(X509Extensions.KeyUsage, True, New KeyUsage(KeyUsage.DigitalSignature Or KeyUsage.DataEncipherment Or KeyUsage.CrlSign Or KeyUsage.KeyCertSign Or KeyUsage.NonRepudiation))

        Dim newCert = gen.Generate(kp.Private)

        'set data
        cadata.MyCertificate = newCert
        cadata.BouncyCastlePrivateKey = DirectCast(kp.Private, Parameters.RsaPrivateCrtKeyParameters)

        PersistenceManager.SaveMyCertificate()
        PersistenceManager.SaveCAData()

        RaiseEvent CertificateGenerated()
    End Sub

    Public Shared Event CertificateGenerated()


    Public Enum CACertificateStatus
        Valid
        NotFound
        Expired
    End Enum

    Public Class KeysNotReadyException
        Inherits Exception
    End Class
End Class
